import store from '../store/index.js'
const ioSocket = ({
	data,
	connect = () => {},
	success = () => {},
	fail = () => {},
	open = () => {},
	close = () => {},
	socketDistance = () => {}
}, ) => {
	let timeout = null;
	let socket = uni.connectSocket({
		url: `ws://gpt.gxmob.cn/websocket/v1/miletus/word/ai?token=${store.state.token}`,
		header: {
			'content-type': 'application/json',
		},
		success: res => {
			console.log(res, 'socketsuccess')
			timeout = setTimeout(() => {
				uni.showToast({
					title: '链接超时，请重试！',
					icon: 'none'
				})
				socket.close({
					reason: '超时'
				})
				socket = null;
			}, 10000)
			connect()
		},
		fail: err => {
			console.log(err, 'err socket')
			fail('connect')
			socket = null
		},
		complete: () => {}
	});
	socket.onOpen((res) => {
		socket.send({
			data: JSON.stringify(data),
			success: res => {
				console.log(res, 'sendSUccess')
			},
			fail: err => {
				console.log(err, 'sendFail')
				fail('open')
				socket = null
			}
		});
	});
	socket.onMessage((res) => {
		if (timeout) {
			clearTimeout(timeout)
			timeout = null
		}
		console.log('收到服务器内容：==>', res.data);
		success(res.data)
	});
	socket.onClose(res => {
		console.log(res, 'res onclose')
		socket = null;
		if (res.reason == '403') {
			store.state.openVip = true;
		}
		close()
	})
	socket.onError(function(res) {
		socket = null;
		fail('error')
		console.log('WebSocket连接打开失败，请检查！', res);
	});
	socketDistance(socket)
}
export default ioSocket